package com.shortlink.admin.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.shortlink.admin.dto.req.shortlink.ShortLinkBatchCreateReqDTO;
import com.shortlink.admin.dto.req.shortlink.ShortLinkCreateReqDTO;
import com.shortlink.admin.dto.req.shortlink.ShortLinkGroupPageReqDTO;
import com.shortlink.admin.dto.req.shortlink.ShortLinkUpdateReqDTO;
import com.shortlink.admin.dto.resp.shortlink.ShortLinkVO;
import com.shortlink.admin.handler.CustomBlockHandler;
import com.shortlink.admin.service.ShortLinkService;
import com.shortlink.common.base.Result;
import com.shortlink.common.base.Results;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 短链接后管控制层
 *
 * @author wp
 */
@RestController
@RequiredArgsConstructor
public class ShortLinkController {
    private final ShortLinkService shortLinkService;

    /**
     * 用户创建短链接
     */
    @PostMapping("/web-api/shortlink/save")
    @SentinelResource(
            value = "create_short-link",
            blockHandler = "createShortLinkBlockHandlerMethod",
            blockHandlerClass = CustomBlockHandler.class
    )
    public Result<Void> createShortLink(@RequestBody ShortLinkCreateReqDTO shortLinkCreate) {
        shortLinkService.createShortLink(shortLinkCreate);
        return Results.success();
    }

    /**
     * 用户批量创建短链接
     */
    @PostMapping("/web-api/shortlink/save/batch")
    public Result<Void> batchCreateShortLink(@RequestBody ShortLinkBatchCreateReqDTO shortLinkBatchCreate) {
        shortLinkService.batchCreateShortLink(shortLinkBatchCreate);
        return Results.success();
    }

    /**
     * 用户修改短链接
     */
    @PutMapping("/web-api/shortlink/update")
    public Result<Void> updateShortLink(@RequestBody ShortLinkUpdateReqDTO shortLinkUpdate) {
        shortLinkService.updateShortLink(shortLinkUpdate);
        return Results.success();
    }

    /**
     * 用户分页查询短链接
     */
    @GetMapping("/web-api/shortlink/page")
    public Result<IPage<ShortLinkVO>> pageShortLink(ShortLinkGroupPageReqDTO shortLinkGroupPage) {
        return Results.success(shortLinkService.pageGroup(shortLinkGroupPage));
    }

    /**
     * 用户删除短链接
     */
    @DeleteMapping("/web-api/shortlink/delete/{id}")
    public Result<Void> remove(@PathVariable Long id) {
        shortLinkService.moveToRecycleBin(id);
        return Results.success();
    }

    /**
     * 用户查询短链接分组内数量
     */
    @GetMapping("/web-api/shortlink/count")
    public Result<Map<Long, Integer>> listGroupShortLinkCount(@RequestParam("groupIds") List<Long> groupIds) {
        return Results.success(shortLinkService.listGroupShortLinkCount(groupIds));
    }
}
